<template>
  <view class="page-container">
    <!-- 顶部导航 -->
    <S1Header title="人员管理" :on-back="onBack" />

    <!-- 搜索栏 -->
    <view class="search-bar">
      <up-search
        v-model="keyword"
        placeholder="搜索姓名/手机号"
        :show-action="false"
        bg-color="#f5f5f5"
      />
    </view>

    <!-- 顶部操作栏 -->
    <view class="toolbar">
      <text class="total-text">
        共 {{ displayList.length }} 人
      </text>
      <view class="toolbar-actions">
        <up-button
          type="warning"
          size="small"
          plain
          @click="handlePermissionManage"
          style="margin-right: 12rpx;"
        >
          <up-icon name="setting" size="16" style="margin-right: 4px;" />
          权限管理
        </up-button>
        <up-button type="primary" size="small" @click="handleAdd">
          <up-icon name="plus" size="16" style="margin-right: 4px;" />
          添加
        </up-button>
      </view>
    </view>

    <!-- 人员列表 -->
    <view class="list-wrapper">
      <view
        v-for="item in displayList"
        :key="item.id"
        class="person-item"
      >
        <view class="avatar" :class="{ inactive: item.status !== 1 }">
          <up-icon name="account-fill" size="40" color="#fff" />
        </view>
        <view class="info">
          <view class="name-row">
            <text class="name">
              {{ item.name }}
            </text>
            <text class="job-title">
              {{ getGroupTitle(item.group_id) }}
            </text>
            <up-tag
              :text="item.status === 1 ? '启用' : '禁用'"
              :type="item.status === 1 ? 'success' : 'info'"
              size="mini"
            />
          </view>
          <text class="mobile">
            {{ item.mobile }}
          </text>
          <text class="login-time">
            最后登录：{{ formatLoginTime(item.last_login_time) }}
          </text>
        </view>
        <view class="actions">
          <up-button type="primary" size="mini" plain @click="handleEdit(item)">
            编辑
          </up-button>
          <up-button type="error" size="mini" plain @click="handleDelete(item)">
            删除
          </up-button>
        </view>
      </view>

      <!-- 空状态 -->
      <up-empty
        v-if="displayList.length === 0 && !loading"
        mode="data"
        text="暂无收银员"
      >
        <template #bottom>
          <up-button type="primary" size="small" @click="handleAdd">
            立即添加
          </up-button>
        </template>
      </up-empty>

      <!-- 加载状态 -->
      <view v-if="loading" class="loading-wrapper">
        <up-loading-icon mode="circle" />
        <text class="loading-text">
          加载中...
        </text>
      </view>
    </view>

    <!-- 添加/编辑弹窗 -->
    <up-popup
      v-model:show="showDialog"
      mode="center"
      :round="10"
      closeable
      close-icon-pos="top-right"
    >
      <view class="dialog-wrapper">
        <view class="dialog-title">
          {{ dialogTitle }}
        </view>

        <view class="dialog-form">
          <view class="form-item">
            <view class="form-label">
              <text class="required">
                *
              </text>
              姓名
            </view>
            <input v-model="formData.name" class="form-input" placeholder="请输入姓名">
          </view>

          <view class="form-item">
            <view class="form-label">
              <text class="required">
                *
              </text>
              手机号
            </view>
            <input
              v-model="formData.mobile" class="form-input" placeholder="请输入11位手机号" type="number"
              maxlength="11"
            >
          </view>

          <view class="form-item">
            <view class="form-label">
              <text v-if="!isEdit" class="required">
                *
              </text>
              密码
            </view>
            <input
              v-model="formData.password" class="form-input"
              :placeholder="isEdit ? '不修改请留空' : '请设置登录密码'" password
            >
          </view>

          <view class="form-item">
            <view class="form-label">
              <text class="required">
                *
              </text>
              分组
            </view>
            <view class="form-input" @click="showGroupPicker = true">
              <text :class="{ placeholder: !selectedGroupTitle }">
                {{ selectedGroupTitle || '请选择分组' }}
              </text>
              <up-icon name="arrow-down" size="14" color="#c0c4cc" />
            </view>
          </view>
        </view>
        <template #bottom>
          <view class="dialog-footer">
            <up-button style="flex: 1; margin-right: 16rpx;" @click="closeDialog">
              取消
            </up-button>
            <up-button type="primary" style="flex: 1;" @click="handleSubmit">
              确定
            </up-button>
          </view>
        </template>
      </view>
    </up-popup>

    <!-- 分组选择器 -->
    <up-picker
      v-model:show="showGroupPicker"
      :columns="groupColumns"
      @confirm="onGroupConfirm"
      @cancel="showGroupPicker = false"
    />
  </view>
</template>

<script setup lang="ts">
import type { AddCashierReq, CashierGroup, CashierItem, EditCashierReq } from '@/api/user/types';
import { computed, ref } from 'vue';
import { UserApi } from '@/api';
import S1Header from '@/components/S1Header.vue';

// 状态管理
const cashierList = ref<CashierItem[]>([]);
const groupList = ref<CashierGroup[]>([]);
const loading = ref(false);
const showDialog = ref(false);
const showPassword = ref(false);
const isEdit = ref(false);
const showGroupPicker = ref(false);

// 搜索关键字
const keyword = ref('');

// 过滤后的展示列表
const displayList = computed(() => {
  const k = keyword.value.trim();
  if (!k) return cashierList.value;
  return cashierList.value.filter(it => `${it.name}${it.mobile}`.includes(k));
});

// 表单数据
const formData = ref<AddCashierReq | EditCashierReq>({
  name: '',
  mobile: '',
  password: '',
  group_id: 1,
});

// 编辑时的ID
const editId = ref<number | undefined>(undefined);

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑收银员' : '添加收银员');

// 分组选择器数据
const groupColumns = computed(() => [
  groupList.value.map(g => ({ text: g.title, value: g.id })),
]);

// 当前选中的分组名称
const selectedGroupTitle = computed(() => {
  const group = groupList.value.find(g => g.id === formData.value.group_id);
  return group?.title || '';
});

// 返回上一页
const onBack = () => {
  uni.navigateBack();
};

// 加载收银员列表
const loadCashierList = async () => {
  try {
    loading.value = true;
    const res = await UserApi.cashierList({
      limit: 100,
      page: 1,
    });

    if (res.code === 200 && res.data) {
      cashierList.value = res.data.data || [];
    }
    else {
      uni.showToast({
        title: res.msg || '获取列表失败',
        icon: 'none',
      });
    }
  }
  catch (error) {
    console.error('加载收银员列表失败:', error);
    uni.showToast({
      title: '加载失败,请重试',
      icon: 'none',
    });
  }
  finally {
    loading.value = false;
  }
};

// 加载分组列表
const loadGroupList = async () => {
  try {
    const res = await UserApi.getCashierGroup();
    console.log('分组数据:', res);
    if (res.code === 200 && res.data) {
      groupList.value = res.data;
    }
  }
  catch (error) {
    console.error('加载分组列表失败:', error);
  }
};

// 打开添加对话框
const handleAdd = async () => {
  isEdit.value = false;
  editId.value = undefined;
  formData.value = {
    name: '',
    mobile: '',
    password: '',
    group_id: 1,
  };
  await loadGroupList();
  showDialog.value = true;
};

// 打开编辑对话框
const handleEdit = async (item: CashierItem) => {
  isEdit.value = true;
  editId.value = item.id;
  formData.value = {
    name: item.name,
    mobile: item.mobile,
    password: '',
    group_id: item.group_id,
  };
  await loadGroupList();
  showDialog.value = true;
};

// 关闭对话框
const closeDialog = () => {
  showDialog.value = false;
};

// 搜索相关
const onSearch = () => {
};
const clearSearch = () => {
  keyword.value = '';
};
const getAvatarText = (name: string) => name ? name.slice(0, 1) : '员';

// 获取分组名称
const getGroupTitle = (groupId: number) => {
  const group = groupList.value.find(g => g.id === groupId);
  return group?.title || '未知';
};

// 分组选择器确认
const onGroupConfirm = (e: any) => {
  const selected = e.value[0];
  formData.value.group_id = selected.value;
  showGroupPicker.value = false;
};

// 格式化登录时间
const formatLoginTime = (timestamp: number | undefined) => {
  if (!timestamp) return '未登录';
  const date = new Date(timestamp * 1000);
  const now = new Date();
  const diff = now.getTime() - date.getTime();

  // 小于1小时
  if (diff < 3600000) {
    const minutes = Math.floor(diff / 60000);
    return minutes < 1 ? '刚刚' : `${minutes}分钟前`;
  }

  // 小于24小时
  if (diff < 86400000) {
    const hours = Math.floor(diff / 3600000);
    return `${hours}小时前`;
  }

  // 小于7天
  if (diff < 604800000) {
    const days = Math.floor(diff / 86400000);
    return `${days}天前`;
  }

  // 超过7天，显示具体日期
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');

  // 如果是今年，不显示年份
  if (year === now.getFullYear()) {
    return `${month}-${day} ${hour}:${minute}`;
  }
  return `${year}-${month}-${day} ${hour}:${minute}`;
};

// 提交表单
const handleSubmit = async () => {
  // 表单验证
  if (!formData.value.name) {
    uni.showToast({
      title: '请输入收银员名称',
      icon: 'none',
    });
    return;
  }

  if (!formData.value.mobile) {
    uni.showToast({
      title: '请输入手机号',
      icon: 'none',
    });
    return;
  }

  if (!formData.value.password && !isEdit.value) {
    uni.showToast({
      title: '请输入密码',
      icon: 'none',
    });
    return;
  }

  try {
    uni.showLoading({
      title: isEdit.value ? '保存中...' : '添加中...',
      mask: true,
    });

    let res;
    if (isEdit.value && editId.value) {
      // 编辑时调用editCashier
      res = await UserApi.editCashier({
        ...formData.value,
        id: editId.value,
      } as EditCashierReq);
    }
    else {
      // 添加时调用addCashier
      res = await UserApi.addCashier(formData.value as AddCashierReq);
    }

    uni.hideLoading();

    if (res.code === 200) {
      uni.showToast({
        title: isEdit.value ? '修改成功' : '添加成功',
        icon: 'success',
      });
      closeDialog();
      loadCashierList();
    }
    else {
      uni.showToast({
        title: res.msg || '操作失败',
        icon: 'none',
      });
    }
  }
  catch (error) {
    uni.hideLoading();
    console.error('提交失败:', error);
    uni.showToast({
      title: '操作失败,请重试',
      icon: 'none',
    });
  }
};

// 处理权限管理
const handlePermissionManage = () => {
  uni.navigateTo({
    url: '/pages/common/permission/index'
  });
};

// 删除收银员
const handleDelete = (item: CashierItem) => {
  uni.showModal({
    title: '提示',
    content: `确定要删除收银员"${item.name}"吗?`,
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({
            title: '删除中...',
            mask: true,
          });

          const result = await UserApi.delCashier({
            user_id: item.id,
          });

          uni.hideLoading();

          if (result.code === 200) {
            uni.showToast({
              title: '删除成功',
              icon: 'success',
            });
            loadCashierList();
          }
          else {
            uni.showToast({
              title: result.msg || '删除失败',
              icon: 'none',
            });
          }
        }
        catch (error) {
          uni.hideLoading();
          console.error('删除失败:', error);
          uni.showToast({
            title: '删除失败,请重试',
            icon: 'none',
          });
        }
      }
    },
  });
};

// 页面加载时获取数据
onLoad(() => {
  loadGroupList();
  loadCashierList();
});

onShow(() => {
  loadCashierList();
});
</script>

<style scoped lang="scss">
:deep(.u-safe-bottom) {
  display: none;
}

.page-container {
  min-height: 100vh;
  background: #f5f5f5;
}

/* 搜索栏 */
.search-bar {
  padding: 16rpx;
  background: #fff;
}

/* 工具栏 */
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 32rpx;
  background: #fff;
  border-top: 1px solid #eee;
}

.toolbar-actions {
  display: flex;
  gap: 0;
}

.total-text {
  font-size: 28rpx;
  color: #666;
  font-weight: 500;
}

/* 列表区域 */
.list-wrapper {
  padding: 24rpx;
  background: #f5f5f5;
}

/* 人员项 */
.person-item {
  display: flex;
  align-items: center;
  background: #fff;
  padding: 24rpx;
  margin-bottom: 16rpx;
  border-radius: 12rpx;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: #909399;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.avatar.inactive {
  background: #c0c4cc;
}

.avatar-text {
  font-size: 32rpx;
  color: #fff;
  font-weight: 500;
}

.info {
  flex: 1;
  min-width: 0;
}

.name-row {
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;
}

.name {
  font-size: 32rpx;
  color: #303133;
  font-weight: 500;
  margin-right: 12rpx;
}

.mobile {
  font-size: 28rpx;
  color: #909399;
  display: block;
  margin-bottom: 8rpx;
}

.job-title {
  font-size: 24rpx;
  color: #909399;
  margin-right: 12rpx;
}

.login-time {
  font-size: 24rpx;
  color: #c0c4cc;
  display: block;
}

.actions {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
  flex-shrink: 0;
  margin-left: 12rpx;
}

/* 加载状态 */
.loading-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80rpx 0;
}

.loading-text {
  margin-top: 16rpx;
  font-size: 28rpx;
  color: #999;
}

/* 弹窗 */
.dialog-wrapper {
  width: 620rpx;
  padding: 32rpx;
}

.dialog-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #303133;
  margin-bottom: 32rpx;
  text-align: center;
}

.dialog-form {

}

.form-item {
  margin-bottom: 24rpx;
}

.form-item:last-child {
  margin-bottom: 0;
}

.form-label {
  font-size: 28rpx;
  color: #606266;
  margin-bottom: 12rpx;
  display: flex;
  align-items: center;
}

.required {
  color: #f56c6c;
  margin-right: 4rpx;
}

.form-input {
  width: 100%;
  height: 72rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  border: 1px solid #dcdfe6;
  border-radius: 8rpx;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.form-input:focus {
  border-color: #2979ff;
}

.form-input .placeholder {
  color: #c0c4cc;
}

.dialog-footer {
  display: flex;
  margin-top: 32rpx;
  gap: 16rpx;
}
</style>
